package org.example.partner.service.impl;

import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.example.contract.domain.Contract;
import org.example.contract.mapper.ContractMapper;
import org.example.contract.service.IContractService;
import org.example.partner.domain.TenementInfo;
import org.example.partner.mapper.TenementInfoMapper;
import org.example.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.partner.mapper.PartnerMapper;
import org.example.partner.domain.Partner;
import org.example.partner.service.IPartnerService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 合作伙伴Service业务层处理
 *
 * @author 小孟微信：xiaomengcode
 * @date 2024-04-11
 */
@Service
public class PartnerServiceImpl implements IPartnerService
{
    @Autowired
    private PartnerMapper partnerMapper;

    @Autowired
    private TenementInfoMapper tenementInfoMapper;


    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询合作伙伴
     *
     * @param partnerId 合作伙伴主键
     * @return 合作伙伴
     */
    @Override
    public Partner selectPartnerByPartnerId(Long partnerId)
    {
        return partnerMapper.selectPartnerByPartnerId(partnerId);
    }

    /**
     * 查询合作伙伴列表
     *
     * @param partner 合作伙伴
     * @return 合作伙伴
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<Partner> selectPartnerList(Partner partner)
    {
        partner.setDeptId(ShiroUtils.getSysUser().getDeptId()+"");
        return partnerMapper.selectPartnerList(partner);
    }

    @Override
    public List<Partner> queryPartnerList(Partner partner)
    {
        return partnerMapper.selectPartnerList(partner);
    }

    /**
     * 新增合作伙伴
     *
     * @param partner 合作伙伴
     * @return 结果
     */
    @Override
    @Transactional
    @DataScope(deptAlias = "d", userAlias = "u")
    public int insertPartner(Partner partner)
    {
        partner.setDeptId(ShiroUtils.getSysUser().getDeptId()+"");

        //判断是否存在企业名称
        Partner p=new Partner();
        p.setName(partner.getName());
        p.setDeptId(ShiroUtils.getSysUser().getDeptId()+"");
        List<Partner> partners = partnerMapper.selectPartnerList(p);
        if(partners.size()>0){
            throw new ServiceException("已存在："+partner.getName());
        }
        //判断是否存在企业税号
        Partner p1=new Partner();
        p1.setCardNo(partner.getCardNo());
        p1.setDeptId(ShiroUtils.getSysUser().getDeptId()+"");
        List<Partner> partner1 = partnerMapper.selectPartnerList(p);
        if(partner1.size()>0){
            throw new ServiceException("已存在："+partner.getCardNo());
        }

        //判断是否存在手机号
        SysUser sysUser = userMapper.selectUserByPhoneNumber(partner.getLinkPhone());
        if(sysUser!=null){
            throw new ServiceException("已存在："+partner.getLinkPhone());
        }

        //部门
        SysDept dept =new SysDept();
        dept.setParentId(100L);
        dept.setAncestors("100,0");
        dept.setDeptName(partner.getName());
        dept.setLeader(partner.getLinkName());
        dept.setPhone(partner.getLinkPhone());
        deptMapper.insertDept(dept);


        //合伙人
        partner.setDeptId(dept.getDeptId()+"");
        partner.setCreateBy(ShiroUtils.getUserId()+"");
        partner.setCreateTime(DateUtils.getNowDate());
        partnerMapper.insertPartner(partner);

        //租户
        TenementInfo tenementInfo =new TenementInfo();
        tenementInfo.setPartnerId(partner.getPartnerId());
        tenementInfo.setDeptId(ShiroUtils.getSysUser().getDeptId());
        tenementInfoMapper.insertTenementInfo(tenementInfo);

        //初始化登录用户账号
        SysUser user=new SysUser();
        user.setUserName(partner.getLinkName());
        user.setSalt(ShiroUtils.randomSalt());
        user.setLoginName(partner.getLinkPhone());
        user.setPhonenumber(partner.getLinkPhone());
        user.setPassword(passwordService.encryptPassword(partner.getLinkPhone(), Util.PASSWORD, user.getSalt()));
        user.setDeptId(dept.getDeptId());
        userMapper.insertUser(user);


        //角色
        insertUserRole(user.getUserId(), new Long[]{Util.SUPPLIER_ROLE});

        return 1;
    }
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotNull(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 修改合作伙伴
     *
     * @param partner 合作伙伴
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePartner(Partner partner)
    {
        SysDept dept =new SysDept();
        if(!StringUtils.isEmpty(partner.getDeptId())){
            dept.setDeptId(Long.parseLong(partner.getDeptId()));
        }
        dept.setDeptName(partner.getName());
        dept.setLeader(partner.getLinkName());
        dept.setPhone(partner.getLinkPhone());
        deptMapper.updateDept(dept);
        return partnerMapper.updatePartner(partner);
    }

    /**
     * 批量删除合作伙伴
     *
     * @param partnerIds 需要删除的合作伙伴主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePartnerByPartnerIds(String partnerIds)
    {
        int i = 0;
        String[] strArray = Convert.toStrArray(partnerIds);
        for (String partnerId : strArray) {
           i= deletePartnerByPartnerId(Long.parseLong(partnerId));
        }
        return  i;

        //return partnerMapper.deletePartnerByPartnerIds(Convert.toStrArray(partnerIds));
    }

    /**
     * 删除合作伙伴信息
     *
     * @param partnerId 合作伙伴主键
     * @return 结果
     */
    @Override
    public int deletePartnerByPartnerId(Long partnerId) {

        Partner partner = partnerMapper.selectPartnerByPartnerId(partnerId);
        Contract contract = new Contract();
        contract.setBuyDeptId(Long.parseLong(partner.getDeptId()));
        contract.setOwnerDeptId(Long.parseLong(partner.getDeptId()));
        List<Contract> contracts = contractMapper.selectPartnerContractList(contract);
        if(contracts.size()>0){
            throw new ServiceException("该合作伙伴下存在合同，不能删除");
        }

        TenementInfo tenementInfo = new TenementInfo();
        tenementInfo.setDeptId(ShiroUtils.getSysUser().getDeptId());
        tenementInfo.setPartnerId(partnerId);
        return  tenementInfoMapper.deleteTenementInfo(tenementInfo);

    }

    @Override
    public List<Partner> choosePartnerList(Partner partner) {
        return null;
    }
}
